package com.xianyun.site.iblog.blog.executor.query;

import com.alibaba.cola.dto.PageResponse;
import com.github.pagehelper.PageHelper;
import com.xianyun.common.core.utils.bean.BeanUtils;
import com.xianyun.site.iblog.gatewayimpl.database.ArticleMapper;
import com.xianyun.site.iblog.gatewayimpl.database.domainobject.ArticleDO;
import com.xianyun.site.iblog.dto.blog.ArticleListSortQry;
import com.xianyun.site.iblog.dto.blog.data.ArticleDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Component;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.toList;


/**
 * 文章列表分页查询
 * @author mac_zyj
 */
@Component
public class ArticleListSortQryExo {

    @Autowired
    private ArticleMapper articleMapper;

    /**文章转换复制器*/
    private final BeanCopier ArticleCopier = BeanCopier.create(ArticleDO.class, ArticleDTO.class,false);

    public PageResponse<ArticleDTO> execute(@Valid ArticleListSortQry qry){
        List<ArticleDO> articleList = selectArticleByList(qry);
        List<ArticleDTO> resultList = articleDataToDTO(articleList);
        if (!resultList.isEmpty()){
            return PageResponse.of(resultList,resultList.size(), qry.getPageSize(), qry.getPageIndex());
        }
        return PageResponse.of(qry.getPageSize(), qry.getPageIndex());
    }

    private List<ArticleDTO> articleDataToDTO(List<ArticleDO> articleList){
        if (!articleList.isEmpty()){
            return articleList.stream().map(article -> {
                ArticleDTO obj = new ArticleDTO();
                ArticleCopier.copy(article,obj,null);
                return obj;
            }).collect(toList());
        }
        return new ArrayList<>();
    }

    private List<ArticleDO> selectArticleByList(ArticleListSortQry qry){
        ArticleDO searchData = new ArticleDO();
        BeanUtils.copyProperties(qry,searchData);
        PageHelper.startPage(qry.getPageIndex(), qry.getPageSize(), qry.getOrderBy());
        searchData.setQueryParams( initParamsDataMap(qry));
        return articleMapper.selectArticleList(searchData);
    }

    private Map<String,Object> initParamsDataMap(ArticleListSortQry qry){
        Map<String,Object> paramsDataMap =new HashMap<>(9);
        if (null != qry.getBeginTime()){
            paramsDataMap.put("beginTime", qry.getBeginTime());
        }
        if (null != qry.getEndTime()){
            paramsDataMap.put("endTime", qry.getEndTime());
        }
        if (null != qry.getColumnId()){
            paramsDataMap.put("columnId", qry.getColumnId());
        }
        return paramsDataMap;
    }
}
